package com.lmf.juc.forkJoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 演示Fork与Join分支合并框架：需要继承 RecursiveTask类
 *      将一个大的任务拆分成多个子任务进行并行处理，最后将子任务结果合并成最后的计算结果，该算法相当于递归，且是二分查找思路
 */
public class ForkJoinDemo extends RecursiveTask<Integer> {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建ForkJoinDemo对象
        ForkJoinDemo ForkJoinDemo = new ForkJoinDemo(0,100);
        //创建分支合并池对象
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(ForkJoinDemo);
        //获取最终合并之后结果
        Integer result = forkJoinTask.get();
        System.out.println(result);
        //关闭池对象
        forkJoinPool.shutdown();
    }

    //拆分差值不能超过10，计算10以内运算
    private static final Integer VALUE = 10;
    private int begin ;//拆分开始值
    private int end;//拆分结束值
    private int result ; //返回结果

    //创建有参数构造
    public ForkJoinDemo(int begin,int end) {
        this.begin = begin;
        this.end = end;
    }

    //拆分和合并过程
    @Override
    protected Integer compute() {
        //判断相加两个数值是否大于10
        if((end-begin)<=VALUE) {
            //相加操作
            for (int i = begin; i <=end; i++) {
                result = result+i;
            }
        } else {//进一步拆分
            //获取中间值
            int middle = (begin+end)/2;
            //拆分左边
            ForkJoinDemo task01 = new ForkJoinDemo(begin,middle);
            //拆分右边
            ForkJoinDemo task02 = new ForkJoinDemo(middle+1,end);
            //调用方法拆分
            task01.fork();//进行拆分,压入队列
            task02.fork();
            //合并结果
            result = task01.join()+task02.join();
        }
        return result;
    }
}
